<template>
    <div style="margin-top: 20px;margin-left: 15px">
    <el-input style="width: 330px" v-model="filterText" placeholder="请输入配置名称进行搜索" clearable>
      <template #append>
        <el-button type="primary" @click="searchClick">查询</el-button>
      </template>
    </el-input>
    <el-button
      v-if="setButton"
      type="warning"
      style="float: right;margin-right: 15px"
      @click="handleClose"
      icon="el-icon-close"
        >关闭窗口
    </el-button>
    <el-button
      v-if="setButton"
      type="primary"
      style="float: right;margin-right: 5px"
      @click="handelSettingDlg"
      icon="el-icon-check"
        >确认选择
    </el-button>
    <el-button
      v-else
      type="primary"
      style="float: right;margin-right: 15px"
      @click="popup('add')"
      icon="el-icon-plus"
        >新增预设
    </el-button>
  </div>
  <el-scrollbar height="calc(100vh - 150px)">
    <div style="margin: 15px">
	    <el-table ref="table" highlight-current-row :data="presettingList" style="width: 100%" size="mini" border empty-text="暂无数据" @selection-change="selectSetChange">
        <el-table-column  type="selection" ></el-table-column>
        <el-table-column label="序号" align="center" width="60">
          <template #default="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="配置名称"  align="center" width="250"></el-table-column>
        <el-table-column prop="taskType" label="任务类型"  width="120" align="center">
          <template #default="scope">
            <el-tag effect="dark" v-if="scope.row.taskType==='10'">{{ taskTypeMap[scope.row.taskType] || scope.row.taskType }}</el-tag>
            <el-tag v-else type="success" effect="dark">{{ taskTypeMap[scope.row.taskType] || scope.row.taskType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="logMode" label="日志模式" align="center" width="200">
          <template #default="scope">
            <span>{{ logModeMap[scope.row.logMode] || scope.row.logMode }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="control" label="控制模式" align="center" width="150">
          <template #default="scope">
            <span>{{ controlMap[scope.row.control] || scope.row.control }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="pressureMode" label="压测模式" align="center" width="150">
          <template #default="scope">
            <span>{{ pressureModeMap[scope.row.pressureMode] || scope.row.pressureMode }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="serverNames" label="运行机器" align="center" width="300">
          <template #default="scope">
            <el-tag v-for="item in scope.row.serverNames" :key="item" type="info" style="margin-right: 5px">{{ item }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="timeUnit" label="时长单位" align="center" >
          <template #default="scope">
            <span>{{ timeUnitMap[scope.row.timeUnit] || scope.row.timeUnit }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人"  align="center" width="150"></el-table-column>
        <el-table-column label="创建时间"  align="center" width="170">
          <template #default="scope">
            {{ $tools.rTime(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column v-if="setButton === false" label="操作"  align="center" width="260px" fixed="right">
          <template #default="scope">
              <el-button @click="copyPresetting(scope.row)" type="warning" size="mini" plain icon="el-icon-copy-document" >复制</el-button>
              <el-button @click='popup("edit",scope.row)' type="primary" size="mini" plain icon="el-icon-edit-outline">编辑</el-button>
              <el-button @click="delPresetting(scope.row.id)"  size="mini" icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination  background layout="total, prev, pager, next, jumper"
                    @current-change="currentPages"
                    :default-page-size="100"
                    :total="pages.count"
                    :current-page="pages.current"
                   next-text="下一页" prev-text="上一页">
      </el-pagination>
    </div>
  </el-scrollbar>
  <!--  弹窗-->
  <el-dialog :title="dialogTitle" v-model="dialogVisible"  :before-close="closeDialog" top="40px" destroy-on-close custom-class="class_dialog">
    <div class="system-icon-content">
        <el-form :model="configForm"  :rules="rulesConfig" ref="ConfigRef" label-width="95px" >
            <div class="form-container">
              <el-scrollbar height="calc(100vh - 250px)">
                <div class="form-column">
                <el-form-item label="任务类型：" prop="taskType">
                  <el-radio-group v-model="selectTaskType">
                    <el-radio  label="10">
                      普通任务
                    </el-radio>
                    <el-radio  label="20">
                      定时任务
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item prop="name" label="配置名称：" >
                  <el-input v-model="configForm.name" placeholder="请输入配置名称"></el-input>
                </el-form-item>
                <el-form-item v-if="configForm.taskType==='20'" label="时间配置：" prop="rule">
                  <el-popover
                    v-model:visible="cronVisible"
                    placement="bottom-start"
                    width="30">
                    <template #reference>
                      <el-input
                        v-model="configForm.rule"
                        clearable
                        readonly
                        placeholder="请选择定时任务时间配置"
                        @click="cronFun"
                      />
                    </template>
                    <timerTaskCron
                      :runTimeStr="configForm.rule"
                      @closeTime="closeRunTimeCron"
                      @runTime="runTimeCron"
                    >
                      </timerTaskCron>
                  </el-popover>
                </el-form-item>
                <el-form-item prop="logMode" label="日志模式：" >
                  <el-select  v-model="selectedLogMode" placeholder="请选择日志模式" style="width: 100%">
                    <el-option label="关闭" value=0></el-option>
                    <el-option label="开启-全部日志" value=10></el-option>
                    <el-option label="开启-仅成功日志" value=20></el-option>
                    <el-option label="开启-仅失败日志" value=30></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="控制模式：" prop="control">
                  <el-select v-model="selectControlMode" placeholder="请选择控制模式" style="width: 100%">
                    <el-option label="集合模式" value=10></el-option>
                    <el-option label="单独模式" value=20></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="压测模式：" prop="pressureMode">
                  <el-select v-model="selectPressureMode" placeholder="请选择压测模式" style="width: 100%">
                    <el-option label="并发模式" value='10'></el-option>
                    <el-option label="阶梯模式" value='20'></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="时长单位：" prop="pressureMode">
                  <el-select v-model="configForm.timeUnit" placeholder="请选择时长单位" style="width: 100%">
                    <el-option label="s" value="s"></el-option>
                    <el-option label="m" value="m"></el-option>
                    <el-option label="h" value="h"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="思考时间：" prop="thinkTime">
                  <el-select v-model="selectTimeType" placeholder="请选择时间类型" style="width: 30%">
                    <el-option label="固定" value='10'></el-option>
                    <el-option label="随机" value='20'></el-option>
                  </el-select>
                  <span v-if="configForm.thinkTimeType === '20'">
                    <el-input-number
                      v-model="configForm.thinkTime[0]"
                      :min="0"
                      :max="999"
                      size="small"
                      controls-position="right"
                      @change="handleChange"
                      style="width: 90px;margin-left: 10px"
                    />
                    <span style="margin-right: 5px;margin-left: 5px">-</span>
                    <el-input-number
                      v-model="configForm.thinkTime[1]"
                      :min="0"
                      :max="999"
                      size="small"
                      controls-position="right"
                      @change="handleChange"
                      style="width: 90px"
                    />
                  </span>
                  <span v-else>
                    <el-input-number
                      v-model="configForm.thinkTime[0]"
                      :min="0"
                      :max="999"
                      size="small"
                      controls-position="right"
                      @change="handleChange"
                      style="width: 90px;margin-left: 10px"
                    />
                  </span>
                </el-form-item>
                <el-card v-if="configForm.pressureMode==='10'" style="background-color: #f5f7f9" class="card" shadow="always">
                  <el-form label-width="120px" :model="FormConcurrency"  :rules="rulesConcurrencyMode" ref="CaseRef">
                    <el-form-item label="并发用户数：" prop="concurrencyNumber">
                      <el-input v-model="FormConcurrency.concurrencyNumber"></el-input>
                    </el-form-item>
                    <el-form-item label="并发数步长：" prop="concurrencyStep">
                      <el-input v-model="FormConcurrency.concurrencyStep"></el-input>
                    </el-form-item>
                    <el-form-item label="持续时长：" prop="lastLong">
                      <el-input v-model="FormConcurrency.lastLong"></el-input>
                    </el-form-item>

                  </el-form>
                </el-card>
                <el-card v-if="configForm.pressureMode==='20'" style="margin-left: 7px;margin-right: 4px;background-color: #f5f7f9" class="card" shadow="always">
                  <el-form label-width="125px" :model="FormLadder" :rules="rulesLadderMode" ref="CaseRef">
                    <div v-for="(ladder, index) in FormLadder.ladders" :key="index">
                      <div style="color: #606266; display: flex; align-items: center; justify-content: space-between;">
                        <span>阶梯{{ index + 1 }}</span>
                        <el-button
                          :disabled="index < 1"
                          size="mini"
                          type="text"
                          @click="removeLadder(index)"
                        >
                          删除
                        </el-button>
                      </div>
                      <el-form-item label="并发用户数：" :prop="'ladders.' + index + '.concurrencyNumber'">
                        <el-input v-model="ladder.concurrencyNumber"></el-input>
                      </el-form-item>
                      <el-form-item label="并发数步长：" :prop="'ladders.' + index + '.concurrencyStep'">
                        <el-input v-model="ladder.concurrencyStep"></el-input>
                      </el-form-item>
                      <el-form-item label="阶梯持续时长：" :prop="'ladders.' + index + '.lastLong'">
                        <el-input v-model="ladder.lastLong"></el-input>
                      </el-form-item>
                    </div>
                  </el-form>
                  <el-button  style="width: 100%;margin-top: 20px; background-color: #ecf5ff; color: #409eff;" @click="addLadder" >
                    add Data
                  </el-button>
                </el-card>
              </div>
              </el-scrollbar>
              <div class="form-column">
                <el-form-item label="运行机器：" prop="resource">
                  <el-radio-group v-model="configForm.resource">
                    <el-radio  label="10" @click="defaultServer">默认
                      <el-tooltip content="使用机器管理中默认机器运行" :enterable="false" placement="top">
                        <i class="el-icon-question" style="color: #909399; font-size: 16px;"></i>
                      </el-tooltip>
                    </el-radio>
                    <el-radio  label="20" >
                      自定义
                      <el-tooltip content="支持选择多机器分布式运行" :enterable="false" placement="top">
                        <i class="el-icon-question" style="color: #909399; font-size: 16px;"></i>
                      </el-tooltip>
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-table
                    v-if="configForm.resource==='20'"
                    height="200"
                    :data="serverData"
                    style="width: 100%; margin-top: 15px; margin-bottom: 15px"
                    border="true"
                    @selection-change="handleSelectionChange"
                    ref="serverTable"
                >
                <el-table-column type="selection" width="40px" />
                <el-table-column align="center" prop="name" label="机器名称"  />
                <el-table-column align="center" prop="host_ip" label="IP" width="130px"/>
              </el-table>
              </div>
            </div>
          </el-form>
        <div slot="footer" class="dialog-footer" style="text-align: center;">
          <el-button @click="closeDialog" >取 消</el-button>
          <el-button v-if="dialogTitle === '添加预设'" type="primary" @click="clickAdd" >保 存</el-button>
          <el-button v-if="dialogTitle === '编辑预设'" type="primary" @click="clickUpdate" >保 存</el-button>
      </div>
    </div>
  </el-dialog>

</template>

<script>
import timerTaskCron from "@/components/common/timerTaskCron";
import {mapMutations, mapState} from "vuex";
export default {
  props: {
    setButton: {
      type: Boolean,
      default: false
    },
    taskType: {
      type: String
    }
  },
  computed: {
    ...mapState({
      server: state => state.server,
      pro: state => state.pro
    }),
    username() {
			return window.sessionStorage.getItem('username');
		},
    selectedLogMode: {
      get() {
        return this.configForm.logMode.toString();
      },
      set(value) {
        this.configForm.logMode = Number(value);
      }
    },
    selectPressureMode: {
      get() {
        return this.configForm.pressureMode.toString();
      },
      set(value) {
        this.configForm.pressureMode = value;
      }
     },
    selectControlMode: {
      get() {
        return this.configForm.control.toString();
      },
      set(value) {
        this.configForm.control = Number(value);
      }
     },
    selectTaskType: {
      get() {
        return this.configForm.taskType.toString();
      },
      set(value) {
        this.configForm.taskType = value;
      }
    },
    selectTimeType: {
      get() {
        return this.configForm.thinkTimeType.toString();
      },
      set(value) {
        this.configForm.thinkTimeType = value;
      }
     },

  },
  components: {
	  timerTaskCron
  },
  watch: {
    setButton(newVal) {
      if (newVal === true) {
        this.getPresetting(1); // 触发查询
      }
    },
    'configForm.thinkTimeType'(newType) {
      if (newType === '20') {
        this.configForm.thinkTime = [this.configForm.thinkTime[0], this.configForm.thinkTime[1]];
      } else {
        this.configForm.thinkTime = [this.configForm.thinkTime[0]];
      }

    }

  },

  data() {
    return {
        // 状态码映射
        taskTypeMap: {'10': '普通任务', '20': '定时任务'},
        logModeMap: {'0':'关闭','10': '开启-全部日志', '20': '开启-仅成功日志', '30': '开启-仅失败日志'},
        pressureModeMap: {'10': '并发模式', '20': '阶梯模式'},
        timeUnitMap: {'s': '秒', 'm': '分钟', 'h': '小时'},
        controlMap: {'10': '集合模式', '20': '单独模式'},

        SettingDlg: false,
        cronVisible: false,
        dialogVisible:false,
        importSetData: '',
        filterText:'',
        dialogType: '', // 对话框类型，用于区分不同类型的对话框
        dialogTitle: '', // 对话框标题，根据不同类型动态设置
        presettingList: [],
        serverData: [],
        defaultSelection : [],
        Selection : [],
        configForm: {
        name:'',
        rule:'',
        taskType: '10',
        logMode: '0',
        pressureMode: '10',
        timeUnit: 's',
        control:'20',
        resource: '10',
        pressureConfig:{},
        serverArray:[],
        project: '',
        creator:'',
        thinkTimeType:'10',
        thinkTime:[0]
      },
      FormConcurrency:{
          lastLong:'',
          concurrencyNumber:'',
          concurrencyStep:''
        },
      FormLadder: {
        ladders: [
          { concurrencyNumber: '', concurrencyStep: '', lastLong: '' }
        ]
      },

        pages: {
          count: 0,
          current: 1
        },
        rulesConfig: {
          name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
          thinkTime: [{ required: true, message: '请输入思考时间', trigger: 'blur' }]

        },
        rulesConcurrencyMode: {
          lastLong: [{ required: true, message: '请输入持续时长', trigger: 'blur' }],
          concurrencyNumber: [{ required: true, message: '请输入并发数', trigger: 'blur' }],
          concurrencyStep: [{ required: true, message: '请输入步长', trigger: 'blur' }]
        },
        rulesLadderMode: {},
    }
  },
  methods: {
    currentPages(currentPage) {
      this.getPresetting(1)
      this.pages.current = currentPage

  },

    cronFun() {
     this.cronVisible = true;
    },

    closeRunTimeCron(isClose) {
      this.cronVisible = isClose;
    },

    runTimeCron(cron) {
      this.configForm.rule= cron;
    },

    async getPresetting(page,name) {
     const response =await this.$api.getPresetting({
       project_id: this.pro.id,
       isSetting: false,
       page: page,
       name: name,
       taskType:this.taskType
     })
     if (response.status ===200){
				this.presettingList = response.data.result;
				this.pages = response.data;
        // this.configForm.serverArray = presettingList.serverArray;

			}
    },

    handleSelectionChange(selectedRows) {
      // 选择的行可能包含多个对象
      this.configForm.serverArray = selectedRows.map(row => row.id);

    },

    handelSettingDlg(){
      if (this.importSetData){
        this.$emit('set-dlg', this.SettingDlg);
        this.$emit('set-data', this.importSetData);
        this.taskType = ''
      }
      else{
        this.handleClose();
      }
    },
    handleClose() {
      this.$emit('set-dlg', this.SettingDlg);
      this.taskType = ''
    },

    selectSetChange(selection) {
      if (selection.length > 1) {
        // 如果选择了多个项，取消选中所有之前的选项
        this.$refs.table.clearSelection();
        // 只保留最后一个选择的项
        this.$refs.table.toggleRowSelection(selection[selection.length - 1], true);
      }
      if (selection.length === 1) {
        this.importSetData = selection[0] || null;
        console.log('importSetData',this.importSetData)
      }
      else{
        this.importSetData = selection[1] || null;
        console.log('importSetData',this.importSetData)
      }
    },


    delPresetting(id) {
    this.$confirm('此操作将永久删除该设置, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        const response = await this.$api.delPresetting(id)
        if(response.status ===204){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          // 刷新页面
          this.getPresetting(1);
        }
      })
      .catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
  },

    dataSubmit() {
      const params = {...this.configForm}
      // 删除普通任务中的rule参数
      if (params.taskType === '10') delete params.rule;

      if (params.pressureMode === '10') {
        params.pressureConfig = this.FormConcurrency;
        const { ladders, ...rest } = params.pressureConfig;
        params.pressureConfig = rest;
      } else if (params.pressureMode === '20') {
        params.pressureConfig = this.FormLadder;
        const { ...rest } = params.pressureConfig;
        params.pressureConfig = rest;
      }

      return params;
    },

    async clickUpdate() {
      this.$refs.ConfigRef.validate(async vaild => {
      // 判断是否验证通过，不通过则直接retrue
      if (!vaild) return;
      const params = this.dataSubmit()
      const response = await this.$api.updatePresetting(params.id,params);
      if (response.status === 200) {
        this.$message({
          type: 'success',
          message: '修改成功',
          duration: 1000
       });
        this.closeDialog()
      }
      })
    },

    async clickAdd() {
      this.$refs.ConfigRef.validate(async vaild => {
      if (!vaild) return;

      const params = this.dataSubmit()

      const response = await this.$api.createPresetting(params);
      if (response.status === 201) {
        this.$message({
          type: 'success',
          message: '添加成功',
          duration: 1000
        });
        this.closeDialog()
      }
      })
    },

    async popup(type,data) {
      this.dialogType = type;
      this.dialogVisible = true;
      // 根据不同的对话框类型设置标题
      switch (type) {
        case 'add':
          this.dialogTitle = '添加预设';
          this.configForm.creator = this.username;
          this.configForm.project = this.pro.id;
          await this.getServerData(type);

          break;

        case 'edit':
          this.dialogTitle = '编辑预设';
          this.configForm = {...data};
          if (data.pressureMode === '10') {this.FormConcurrency = data.pressureConfig}else {this.FormLadder = data.pressureConfig}
          await this.getServerData(type);
          this.$nextTick(()=>{
             if (this.$refs.serverTable) {
                  this.Selection.forEach(row => {
                      this.$refs.serverTable.toggleRowSelection(row, true);
                  });
              } else {
                  console.error('serverTable is undefined');
              }
          });
          this.setRules()
          break;

        default:
          this.dialogTitle = '';
          break;
      }
    },

    defaultServer() {
        this.defaultSelection = this.serverData.filter(item => item.default_code === true);
        this.handleSelectionChange(this.defaultSelection)
    },

    async getServerData(type) {
     const response = await this.$api.getServers(this.pro.id,1)
     if (response.status ===200){
				this.serverData = response.data.result;
        if (type==='add') {
          // 筛选出 default_code 为 true 的项
          this.defaultSelection = this.serverData.filter(item => item.default_code === true);
          this.handleSelectionChange(this.defaultSelection)
        }
        else if (type === 'edit') {
            const selectedIds = this.configForm.serverArray;
            this.Selection = this.serverData.filter(item => selectedIds.includes(item.id));
        }}
    },

    searchClick() {
     this.getPresetting(1,this.filterText);
    },

    closeDialog() {
      this.dialogVisible = false;
      this.configForm = {
                          name:'',
                          rule:'',
                          taskType: '10',
                          logMode: '0',
                          pressureMode: '10',
                          timeUnit: 's',
                          control:'20',
                          resource: '10',
                          pressureConfig:{},
                          serverArray:[],
                          project: '',
                          creator:'',
                          thinkTimeType: '10',
                          thinkTime:[0]
                        };
      this.FormConcurrency = {
                  lastLong:'',
                  concurrencyNumber:'',
                  concurrencyStep:''
      };
      this.FormLadder = {
        ladders: [
          { concurrencyNumber: '', concurrencyStep: '', lastLong: '' }
        ]
      };
      this.getPresetting(1);
    },

    async copyPresetting(data) {
      const params = {...data}
      params.name = params.name + '_副本'
      params.creator = this.username
      params.project = this.pro.id
      delete params.id
      delete params.update_time
      delete params.create_time

      const response = await this.$api.createPresetting(params);
      if (response.status === 201) {
        this.$message({
          type: 'success',
          message: '复制成功',
          duration: 1000
        });
        this.closeDialog()
      }
    },
    addLadder() {
      this.FormLadder.ladders.push({
        concurrencyNumber: '',
        concurrencyStep: '',
        lastLong: ''
      });
      this.setRules()
    },

    setRules() {
      // 动态生成验证规则
      const ladderRules = {};
      // 遍历 FormLadder.ladders 数组，为每个阶梯项动态设置规则
      this.FormLadder.ladders.forEach((_, index) => {
        ladderRules[`ladders.${index}.concurrencyNumber`] = [
          { required: true, message: '并发用户数不能为空', trigger: 'blur' },
        ];
        ladderRules[`ladders.${index}.concurrencyStep`] = [
          { required: true, message: '并发数步长不能为空', trigger: 'blur' },
        ];
        ladderRules[`ladders.${index}.lastLong`] = [
          { required: true, message: '阶梯持续时长不能为空', trigger: 'blur' },
        ];
      });

      // 设置 rulesLadderMode 的值
      this.rulesLadderMode = ladderRules;
    },

    removeLadder(index) {
      if (this.FormLadder.ladders.length > 1) {
        this.FormLadder.ladders.splice(index, 1);
        this.setRules();
      }
    },

  },

mounted() {this.setRules()},
created() {
    this.getPresetting(1)
  }
}
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
.dialog-footer {
  display: flex;
  justify-content: right;
  margin-top: 10px;
}
.form-container {
  display: flex;
  justify-content: space-between;
}
.form-column {
  flex: 1;
  margin: 0 10px;
}
</style>